package com.sskj.hangqing.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ReplacementTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.SlideCoinBean;
import com.sskj.hangqing.http.HttpConfig;
import com.sskj.hangqing.presenter.SpecialCoinFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.enums.ColorEnum;
import com.sskj.lib.util.ImageUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

@SuppressWarnings("unchecked")
@Route(path = RConfig.HANG_FRAGMENT_SPECIAL_COIN)
public class SpecialCoinFragment extends BaseFragment<SpecialCoinFragmentPresenter> {
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.viewDot0)
    View viewDot0;
    @BindView(R2.id.viewDot1)
    View viewDot1;
    @BindView(R2.id.viewDot2)
    View viewDot2;
    HashMap<Integer, View> integerViewHashMap = new HashMap<>();
    @BindView(R2.id.recycle_up)
    RecyclerView recyclerView;
    private SlideCoinBean slideCoinBean;
    private ArrayList<SlideCoinBean> slideCoinBeans;
    private int changePos;
    List<CoinBean> data;
    private ArrayList<String> specialCoin;
    private HashMap<String, Integer> specialCoinMap;
    private SlimAdapter adapter;


    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_special_coin;
    }

    @Override
    public SpecialCoinFragmentPresenter getPresenter() {
        return new SpecialCoinFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);

        System.out.println(App.INSTANCE.getString(R.string.hangqingspecialCoinFragment1));
//        initRecySlide();
    }

    @Override
    public void initData() {
//        specialCoinMap = new HashMap<>();
//        specialCoinMap.put("BTC/USDT", 1);
//        specialCoinMap.put("ETH/USDT", 2);
//        specialCoinMap.put("EOS/USDT", 3);
//        specialCoin = new ArrayList<>();
//        specialCoin.add("BTC/USDT");
//        specialCoin.add("ETH/USDT");
//        specialCoin.add("EOS/USDT");
        data = new ArrayList<>();

        initRecycle();
        mPresenter.getData();
    }


    private void initRecycle() {
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        adapter = SlimAdapter.create().register(R.layout.hang_item_home, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean o, IViewInjector iViewInjector, List list) {

                String data = o.getCode().replace("_", "/");
                TextView textView = (TextView) iViewInjector.findViewById(R.id.tvCoinTypeFirst);
                textView.setTransformationMethod(new A2A());
                textView.setText(data);
                boolean up = Double.parseDouble(TextUtils.isEmpty(o.getClose()) ? "0" : o.getClose()) -
                        Double.parseDouble(TextUtils.isEmpty(o.getOpen()) ? "0" : o.getOpen()) >= 0;
                iViewInjector.text(R.id.tvCoinUSDTFirst, TextUtils.isEmpty(o.getPrice()) ? "0" : o.getPrice())
                        .text(R.id.tvCoinRmbFirst, "≈" + o.getCnyPrice() + " CNY")
                        .text(R.id.tvCoinRateFirst, o.getChangeRate())
                        .textColor(R.id.tvCoinUSDTFirst, o.isUp() ? ContextCompat.getColor(getContext(), R.color.libUpColor) :
                                ContextCompat.getColor(getContext(), R.color.libDownColor))
                        .textColor(R.id.tvCoinRateFirst, o.isUp() ? ContextCompat.getColor(getContext(), R.color.libUpColor) :
                                ContextCompat.getColor(getContext(), R.color.libDownColor));
                ImageUtil.setCircleImage(HttpConfig.BASE_IMG_URL + o.getImg(), (ImageView) iViewInjector.findViewById(R.id.ivCoinTypeFirst));

                ClickUtil.click(iViewInjector.findViewById(R.id.hang_main), () -> {
                    ARouter.getInstance().build(RConfig.HANG_MARKET)
                            .withString(Constans.CODE, o.getCode())
                            .withString(Constans.QU, "/USDT")
                            .navigation();
                });
            }
        }).attachTo(recyclerView).updateData(data);
//        ItemClickSupport.addTo(recyclerView)
//                .setOnItemClickListener((recyclerView, i, view) ->
//                        ARouter.getInstance().build(RConfig.HANG_MARKET)
//                                .withString(Constans.CODE, ((CoinBean) adapter.getDataItem(i)).getAreaCode())
//                                .withString(Constans.QU, "/USDT")
//                                .navigation());
    }

    private void initRecySlide() {
        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return 1;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                View inflate;
                if (integerViewHashMap.get(position) == null) {
                    inflate = LayoutInflater.from(getActivity()).inflate(R.layout.hang_include_slide_coin, null, false);
                    container.addView(inflate);
                    integerViewHashMap.put(position, inflate);
                } else {
                    inflate = integerViewHashMap.get(position);
                }

                return inflate;
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                viewDot0.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 0 ? R.drawable.hang_shape_dot_select : R.drawable.hang_shape_dot_unselect));
                viewDot1.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 1 ? R.drawable.hang_shape_dot_select : R.drawable.hang_shape_dot_unselect));
//                viewDot2.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 2 ? R.drawable.app_shape_dot_select : R.drawable.app_shape_dot_unselect));
                super.onPageSelected(position);
            }
        });

    }

    private void updateSlideCoin(SlideCoinBean data, View view) {
        if (view == null) {
            return;
        }
        TextView tvCoinTypeFirst = view.findViewById(R.id.tvCoinTypeFirst);
        TextView tvCoinUSDTFirst = view.findViewById(R.id.tvCoinUSDTFirst);
        TextView tvCoinRateFirst = view.findViewById(R.id.tvCoinRateFirst);
        TextView tvCoinRmbFirst = view.findViewById(R.id.tvCoinRmbFirst);
        TextView tvCoinTypeSecond = view.findViewById(R.id.tvCoinTypeSecond);
        TextView tvCoinUSDTSecond = view.findViewById(R.id.tvCoinUSDTSecond);
        TextView tvCoinRateSecond = view.findViewById(R.id.tvCoinRateSecond);
        TextView tvCoinRmbSecond = view.findViewById(R.id.tvCoinRmbSecond);

        TextView tvCoinTypeThird = view.findViewById(R.id.tvCoinTypeThird);
        TextView tvCoinUSDTThird = view.findViewById(R.id.tvCoinUSDTThird);
        TextView tvCoinRateThird = view.findViewById(R.id.tvCoinRateThird);
        TextView tvCoinRmbThird = view.findViewById(R.id.tvCoinRmbThird);


        tvCoinTypeFirst.setText(data.getTypeFirst());
        tvCoinUSDTFirst.setText(data.getUsdtFirst());
        tvCoinRateFirst.setText(data.getRateFirst());
        tvCoinRmbFirst.setText("≈" + data.getRmbFirst() + Constans.DANWEI);
        tvCoinTypeSecond.setText(data.getTypeSecond());
        tvCoinUSDTSecond.setText(data.getUsdtSecond());
        tvCoinRateSecond.setText(data.getRateSecond());
        tvCoinRmbSecond.setText("≈" + data.getRmbSecond() + Constans.DANWEI);

        tvCoinTypeThird.setText(data.getTypeThird());
        tvCoinUSDTThird.setText(data.getUsdtThird());
        tvCoinRateThird.setText(data.getRateThird());
        tvCoinRmbThird.setText("≈" + data.getRmbThird() + Constans.DANWEI);


        tvCoinRateFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpFirst() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        tvCoinUSDTFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpFirst() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        tvCoinRateSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpSecond() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        tvCoinUSDTSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpSecond() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        tvCoinRateThird.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpThird() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        tvCoinUSDTThird.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpThird() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
    }

    public void updateCoin(List<CoinBean> coinBeanList) {
        if (coinBeanList != null && coinBeanList.size() >= 3) {
            data = coinBeanList.subList(0, 3);
        } else {
            data = coinBeanList;
        }
        adapter.updateData(data);
//        Disposable disposable = Flowable.fromIterable(coinBeanList)
//                .filter(coinBean -> coinBean.getAreaCode() != null && specialCoin.contains(coinBean.getAreaCode()))
//                .map(coinBean -> coinBean.setPriority(specialCoinMap.get(coinBean.getAreaCode())))
//                .toList()
//                .subscribe((coinBeans, throwable) -> this.data = coinBeans);
//        Collections.sort(data, (o1, o2) -> o1.getPriority() - o2.getPriority());
//        slideCoinBeans = new ArrayList<>();
//
//        for (int i = 0; i < data.size(); i++) {
//            switch (i % 3) {
//                case 0:
//                    slideCoinBean = new SlideCoinBean(data.get(i).getAreaCode(), "", "");
//                    slideCoinBeans.add(slideCoinBean);
//                    slideCoinBean.setRateFirst(data.get(i).getChangeRate());
//                    slideCoinBean.setUpFirst(data.get(i).isUp());
//                    slideCoinBean.setUsdtFirst(data.get(i).getPrice());
//                    slideCoinBean.setRmbFirst(data.get(i).getCnyPrice());
//                    break;
//                case 1:
//                    slideCoinBean.setTypeSecond(data.get(i).getAreaCode());
//                    slideCoinBean.setRateSecond(data.get(i).getChangeRate());
//                    slideCoinBean.setUpSecond(data.get(i).isUp());
//                    slideCoinBean.setUsdtSecond(data.get(i).getPrice());
//                    slideCoinBean.setRmbSecond(data.get(i).getCnyPrice());
//
//                    break;
//                case 2:
//                    slideCoinBean.setTypeThird(data.get(i).getAreaCode());
//                    slideCoinBean.setRateThird(data.get(i).getChangeRate());
//                    slideCoinBean.setUpThird(data.get(i).isUp());
//                    slideCoinBean.setUsdtThird(data.get(i).getPrice());
//                    slideCoinBean.setRmbThird(data.get(i).getCnyPrice());
//
//                    break;
//                default:
//                    break;
//            }
//        }
//        for (int i = 0; i < slideCoinBeans.size(); i++) {
//            updateSlideCoin(slideCoinBeans.get(i), integerViewHashMap.get(i));
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean Bean) {
        List<CoinBean> temp = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getCode().equals(Bean.getCode())) {
                temp.add(Bean);
            } else {
                temp.add(data.get(i));
            }
        }
        data = temp;
        adapter.updateData(temp);
//        if (slideCoinBeans == null || data == null || specialCoin == null || !specialCoin.contains(coinBean.getAreaCode()))
//            return;
//        changePos = -1;
//        Disposable disposable = Flowable.fromIterable(data)
//                .filter(stockCoinBean -> stockCoinBean.getAreaCode().equals(coinBean.getAreaCode()))
//                .subscribe(stockCoinBean -> {
//                    changePos = data.indexOf(stockCoinBean);
//                });
//        if (changePos != -1) {
//            int i = changePos / 3;
//            SlideCoinBean slideCoinBean = slideCoinBeans.get(i);
//            switch (changePos % 3) {
//                case 0:
//                    slideCoinBean.setRateFirst(coinBean.getChangeRate());
//                    slideCoinBean.setUpFirst(coinBean.isUp());
//                    slideCoinBean.setUsdtFirst(coinBean.getPrice());
//                    slideCoinBean.setRmbFirst(coinBean.getCnyPrice());
//                    break;
//                case 1:
//                    slideCoinBean.setRateSecond(coinBean.getChangeRate());
//                    slideCoinBean.setUpSecond(coinBean.isUp());
//                    slideCoinBean.setUsdtSecond(coinBean.getPrice());
//                    slideCoinBean.setRmbSecond(coinBean.getCnyPrice());
//                    break;
//                case 2:
//                    slideCoinBean.setRateThird(coinBean.getChangeRate());
//                    slideCoinBean.setUpThird(coinBean.isUp());
//                    slideCoinBean.setUsdtThird(coinBean.getPrice());
//                    slideCoinBean.setRmbThird(coinBean.getCnyPrice());
//
//                    break;
//            }
//            updateSlideCoin(slideCoinBean, integerViewHashMap.get(i));
//        }

    }


    class A2A extends ReplacementTransformationMethod {

        @Override
        protected char[] getOriginal() {
            char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return aa;
        }

        @Override
        protected char[] getReplacement() {
            char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return cc;
        }
    }

}
